package com.igeek.dao;

import com.igeek.domain.Product;
import com.igeek.utils.JDBCTools;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class Productdao {
    QueryRunner qr =new QueryRunner(JDBCTools.getDataSource());
    String sql="";
    public List<Product> gethotProducts() {
        sql="select * from product where is_hot=1 limit 0,9";
        try {
            return qr.query(sql,new BeanListHandler<>(Product.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<Product> getnewProducts() {
        sql="select * from product order by pdate desc limit 0,9";
        try {
            return qr.query(sql,new BeanListHandler<>(Product.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<Product> findproductBycid(String cid) {
        sql="select *from product where cid=?";
        try {
            return qr.query(sql,new BeanListHandler<>(Product.class),cid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<Product> findData(int nowPage, int i, String cid) {
        sql="select *from product where cid=? limit ?,?";
        int offset=(nowPage-1)*i;
        try {
            return qr.query(sql,new BeanListHandler<>(Product.class),cid,offset,i);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int getCount(String cid) {
        sql="select count(*)from product where cid=?";
        Long result=0L;
        try {
            result=qr.query(sql,new ScalarHandler<Long>(),cid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return Integer.parseInt(result+"");
    }

    public Product getProductByPid(String pid) {
        sql="select * from product where pid=?";
        try {
            return qr.query(sql,new BeanHandler<>(Product.class),pid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Product findHistoryProducts(String pids) {
        sql="select *from product p,category c where pid=? and c.cid=p.cid";
        try {
            return qr.query(sql,new BeanHandler<>(Product.class),pids);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
